//
//  SearchViewController.m
//  DolphinMusic
//
//  Created by dllo on 15/3/21.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "SearchViewController.h"
#import "Search.h"
#import "AFNetworking.h"
#import "NetHandler.h"
#import "Singer.h"
#import "SearchTableViewCell.h"
#import "ArtistnameTableViewCell.h"
#import "MusicPlayViewController.h"
#import "SIngerViewController.h"
#import "ListViewController.h"
#import "Flag.h"
#import "AlbumSeachTableViewCell.h"
#import "UIScrollView+MJRefresh.h"
#import "MJRefresh.h"


@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate, UIScrollViewDelegate>

@property(nonatomic , retain)NSString *queryStr;
@property(nonatomic , retain)UITableView *tableview;
@property(nonatomic , retain)UITableView *tableview2;
@property(nonatomic , retain)UITableView *tableview3;
@property(nonatomic , retain)NSMutableArray *arr;
@property(nonatomic , retain)NSMutableArray *arr2;
@property(nonatomic , retain)NSMutableArray *arr3;
@property(nonatomic , retain)UIScrollView *scrollback;
@property(nonatomic , retain)UISegmentedControl *segment;
@property(nonatomic , retain)UISearchBar *searchbar;



@end

@implementation SearchViewController

- (void)dealloc
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center removeObserver:self];
    
    [_queryStr release];
    [_tableview release];
    [_tableview2 release];
    [_tableview3 release];
    [_arr release];
    [_arr2 release];
    [_arr3 release];
    [_scrollback release];
    [_segment release];
    [self.searchbar release];
    [super dealloc];
}

- (NSString *)pinYin

{
    //先转换为带声调的拼音
    NSMutableString *str = [self.queryStr mutableCopy];
    
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    
    //再转换为不带声调的拼音
    
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    
    return str;
}

- (void)SearchStr
{
    NSString *pinyinStr = [[self pinYin] stringByRemovingPercentEncoding];
    
    
    NSString *str = [NSString stringWithFormat:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.0.1&method=baidu.ting.search.catalogSug&format=json&query=%@", pinyinStr];
    
    [NetHandler getDataWithUrl:str completion:^(id dict) {
        
        [self.arr removeAllObjects];
        [self.arr2 removeAllObjects];
        [self.arr3 removeAllObjects];
        
        NSMutableArray *songArr = [dict objectForKey:@"song"];
        NSMutableArray *artistArr = [dict objectForKey:@"artist"];
        NSMutableArray *albumArr = [dict objectForKey:@"album"];
        
        if (pinyinStr != nil && ![pinyinStr isEqualToString:@""]) {
        
        for (NSDictionary *dic in songArr) {
            Song *song = [[Song alloc] init];
            song.song_id = [dic objectForKey:@"songid"];
            song.title = [dic objectForKey:@"songname"];
            song.author = [dic objectForKey:@"artistname"];
            [self.arr addObject:song];
            [song release];
        }
        for (NSDictionary *dic in artistArr) {
            Singer *singer = [[Singer alloc]initWithDictionary:dic];
            singer.ting_uid = [dic objectForKey:@"artistid"];
            singer.avatar_middle = [dic objectForKey:@"artistpic"];
            [self.arr2 addObject:singer];
            [singer release];
            
        }
        for (NSDictionary *dic in albumArr) {
            Album *album = [[Album alloc] init];
            album.title = [dic objectForKey:@"albumname"];
            album.author = [dic objectForKey:@"artistname"];
            album.album_id = [dic objectForKey:@"albumid"];
            album.pic_big = [dic objectForKey:@"artistpic"];
            [self.arr3 addObject:album];
            
            [album release];
        }
        }
        
        [self.tableview reloadData];
        [self.tableview2 reloadData];
        [self.tableview3 reloadData];
    }];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    UIWindow *window = [[[UIApplication sharedApplication] windows] firstObject];
    PlayView *playView = (PlayView*)[window viewWithTag:10001];
    playView.target = self.navigationController;
    
    self.arr = [NSMutableArray array];
    self.arr2 = [NSMutableArray array];
    self.arr3 = [NSMutableArray array];
    
    self.navigationController.navigationBarHidden  = YES;
    
    // 搜索页面背景图
//    UIImageView *imageViews = [[UIImageView alloc] initWithFrame:self.view.bounds];
//    imageViews.image = [UIImage imageNamed:@"searchBG.jpg"];
//    imageViews.userInteractionEnabled = YES;
//    [self.view addSubview:imageViews];
//    [imageViews release];
    
    
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#afdfe4"];
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 20)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    [view1 release];

    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 20, VIEW_WIDTH, 44)];
    view2.backgroundColor = [UIColor colorFromHexCode:@"#33a3dc"];
    view2.clipsToBounds = YES;
    [self.view addSubview:view2];
    [view2 release];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.frame = CGRectMake(0, 20, 50, 44);
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 12, 20, 20)];
    imageView.image = [UIImage imageNamed:@"backButton.png"];
    [leftButton addSubview:imageView];
    [imageView release];
    

    [leftButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    
    
    
    self.searchbar = [[UISearchBar alloc]initWithFrame:CGRectMake(50, -0.5,self.view.frame.size.width - 50 * 2, 45)];
    self.searchbar.placeholder = @"输入歌曲名 , 歌手名 , 专辑";
    self.searchbar.barTintColor = [UIColor colorFromHexCode:@"#33a3dc"];
    self.searchbar.delegate = self;
    [view2 addSubview:self.searchbar];
    [_searchbar release];
    

    
    // 导航标题
    self.segment = [[UISegmentedControl alloc]initWithItems:@[@"歌曲",@"歌手",@"专辑"]];
    self.segment.frame = CGRectMake(0, 64, self.view.frame.size.width, 30);
    self.segment.tintColor = [UIColor whiteColor];
    self.segment.hidden = YES;
    self.segment.selectedSegmentIndex = 0;
    [self.segment addTarget:self action:@selector(segmented:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segment];
    [self.segment release];
    
    // 背景滑动
    self.scrollback = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 94, self.view.frame.size.width, self.view.frame.size.height - 94 - 70.0 / 667 * VIEW_HEIGHT)];
    self.scrollback.backgroundColor = [UIColor clearColor];
    self.scrollback.contentSize = CGSizeMake(self.view.frame.size.width * 3, 0);
    self.scrollback.showsHorizontalScrollIndicator = NO;
    self.scrollback.delegate = self;
    self.scrollback.pagingEnabled = YES;
    [self.view addSubview:self.scrollback];
    [_scrollback release];
    

    
    // 搜索tableview
    
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 10, self.scrollback.frame.size.height)];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.rowHeight = 55;
   
    
    [_tableview  registerClass:[SearchTableViewCell class] forCellReuseIdentifier:@"Alogo"];
    
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableview.showsVerticalScrollIndicator = NO;
    self.tableview.backgroundColor = [UIColor clearColor];
    [self.scrollback addSubview:self.tableview];
    [_tableview release];
    

    self.tableview2 = [[UITableView alloc]initWithFrame:CGRectMake(VIEW_WIDTH, 0, VIEW_WIDTH - 10, self.scrollback.frame.size.height)];
    self.tableview2.delegate = self;
    self.tableview2.dataSource = self;
    [_tableview2  registerClass:[ArtistnameTableViewCell class] forCellReuseIdentifier:@"Blogo"];
    self.tableview2.rowHeight = 60;
    self.tableview2.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview2.showsVerticalScrollIndicator = NO;
    self.tableview2.backgroundColor = [UIColor clearColor];
    
    
    
    [self.scrollback addSubview:self.tableview2];
    [_tableview2 release];

    
    self.tableview3 = [[UITableView alloc]initWithFrame:CGRectMake(VIEW_WIDTH * 2, 0, self.view.frame.size.width - 10, self.scrollback.frame.size.height)];
    self.tableview3.delegate = self;
    self.tableview3.dataSource = self;
    self.tableview3.rowHeight = 60;
    self.tableview3.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableview3  registerClass:[AlbumSeachTableViewCell class] forCellReuseIdentifier:@"Clogo"];
    

    self.tableview3.showsVerticalScrollIndicator = NO;
    self.tableview3.backgroundColor = [UIColor clearColor];
    [self.scrollback addSubview:self.tableview3];
    [_tableview3 release];

   }


- (void)segmented:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0) {
        self.scrollback.contentOffset = CGPointMake(0, 0);
        
    }if (segment.selectedSegmentIndex == 1) {
        
        self.scrollback.contentOffset = CGPointMake(self.view.frame.size.width, 0);
        
    }if (segment.selectedSegmentIndex == 2) {
        
        self.scrollback.contentOffset = CGPointMake(self.view.frame.size.width * 2 , 0);
  
    }

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.segment.selectedSegmentIndex = (self.scrollback.contentOffset.x + VIEW_WIDTH / 2) / VIEW_WIDTH;
}


// cell行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (self.tableview == tableView) {
        return self.arr.count;
    }if (self.tableview2 == tableView) {
        return self.arr2.count;
    }if (self.tableview3 == tableView) {
        return self.arr3.count;
    }
    return 0;
}

// cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( self.tableview == tableView ) {
        
        SearchTableViewCell *cell = [_tableview dequeueReusableCellWithIdentifier:@"Alogo"];
        Song *song = [self.arr objectAtIndex:indexPath.row];
        cell.backgroundColor = [UIColor clearColor];
        cell.song = song;
    return cell;
    }
    if (self.tableview2 == tableView) {
        
        ArtistnameTableViewCell *cell = [_tableview2 dequeueReusableCellWithIdentifier:@"Blogo"];
        Singer *sing = [self.arr2 objectAtIndex:indexPath.row];
        cell.backgroundColor = [UIColor clearColor];
        cell.singer = sing;
        return cell;
    }
    if (self.tableview3 == tableView) {
        
        AlbumSeachTableViewCell *cell = [_tableview3 dequeueReusableCellWithIdentifier:@"Clogo"];
        Album *album = [self.arr3 objectAtIndex:indexPath.row];
        cell.album = album;
        cell.backgroundColor = [UIColor clearColor];
        
        return cell;
    }
   return nil;
}


// 点击Search收回键盘
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [searchBar resignFirstResponder];
}
// 点击空白回收键盘
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.searchbar resignFirstResponder];
}


// text赋值
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText != nil && ![searchText isEqualToString:@""]) {
        self.segment.hidden = NO;
        self.tableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        self.tableview.separatorColor = [UIColor blackColor];
        
        self.tableview2.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        self.tableview2.separatorColor = [UIColor blackColor];
        
        self.tableview3.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        self.tableview3.separatorColor = [UIColor blackColor];
        

    }else {
        self.segment.hidden = YES;
        self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        self.tableview2.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        self.tableview3.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    
    searchText = [searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.queryStr = searchText;
    [self SearchStr];
    
}


// button返回方法
- (void)buttonAction:(UIButton *)button
{
    Flag *flag = [Flag shareInstance];
    [self.tabBarController setSelectedIndex:flag.flag];
}

// tableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.tableview == tableView ) {
        MusicPlayViewController *musicVC = [MusicPlayViewController shareInstance];
        musicVC.playSongArr = [NSMutableArray array];
        for (Song *song1 in self.arr) {
            [musicVC.playSongArr addObject:song1.song_id];
        }
         Song *song = [self.arr objectAtIndex:indexPath.row];
        musicVC.playingNumber = indexPath.row;
        musicVC.type = @"music";
        musicVC.songID = song.song_id;
    }
    if (self.tableview2 == tableView) {
        SIngerViewController *singerview = [[SIngerViewController alloc]init];
        Singer *singer = [self.arr2 objectAtIndex:indexPath.row];
        NSString *addressStr = [NSString stringWithFormat:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.0.1&method=baidu.ting.search.merge&format=json&query=%@&page_no=1&page_size=30&type=-1&data_source=0&use_cluster=1", singer.name];
        
        [NetHandler getDataWithUrl:addressStr completion:^(id dict) {
            NSDictionary *firstDic = [dict objectForKey:@"result"];
            NSDictionary *secondDic = [firstDic objectForKey:@"artist_info"];
            NSArray *thirdArr = [secondDic objectForKey:@"artist_list"];
            NSDictionary *fourthDic = [thirdArr firstObject];
            
            Singer *singerNext = [[Singer alloc] initWithDictionary:fourthDic];
            singerNext.avatar_big = [fourthDic objectForKey:@"avatar_middle"];
            singerview.singer = singerNext;
            [self.navigationController pushViewController:singerview animated:YES];
        }];
        
    }
if (self.tableview3 == tableView) {
        ListViewController *albumView = [[ListViewController alloc]init];
        Album *album = [self.arr3 objectAtIndex:indexPath.row];
        NSString *str3 = [NSString stringWithFormat:@"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.0.1&method=baidu.ting.album.getAlbumInfo&format=json&album_id=%@", album.album_id];
    albumView.addressStr = str3;
    [self.navigationController pushViewController:albumView animated:YES];
    }
}


- (void)viewDidAppear:(BOOL)animated
{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    UIButton *button = (UIButton *)[window viewWithTag:1000];
    button.hidden = YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
